
import PyQt6
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtWidgets import QWidget,QApplication,QMessageBox
import sys
import pandas as pd
import os
import re
import sqlite3
from object_class import Student
from utils_func import log_xml,log_json,log_db
import cv2


class Ui_Form(QWidget):

    def __init__(self):
        super(Ui_Form, self).__init__()
        self.setWindowFlag(QtCore.Qt.WindowType.MSWindowsFixedSizeDialogHint)
        self.setupUi(self)

        self.addstu_button.clicked.connect(self.add)
        self.cancelstu_button.clicked.connect(self.reset)
        self.photo_button.clicked.connect(self.take_photo)  # 连接拍照按钮
        self.photo = None  # 初始化照片数据

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(429, 422)
        self.formLayoutWidget = QtWidgets.QWidget(parent=Form)
        self.formLayoutWidget.setGeometry(QtCore.QRect(70, 30, 281, 221))
        self.formLayoutWidget.setObjectName("formLayoutWidget")
        self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
        self.formLayout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
        self.formLayout.setFieldGrowthPolicy(QtWidgets.QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        self.formLayout.setContentsMargins(10, 10, 10, 10)
        self.formLayout.setHorizontalSpacing(1)
        self.formLayout.setVerticalSpacing(10)
        self.formLayout.setObjectName("formLayout")
        self.label = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label.setObjectName("label")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label)
        self.lineEdit = QtWidgets.QLineEdit(parent=self.formLayoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit)
        self.label_2 = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.formLayoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_2)
        self.label_3 = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_3)
        self.label_4 = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label_4.setObjectName("label_4")
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_4)
        self.sexLayout_2 = QtWidgets.QFormLayout()
        self.sexLayout_2.setObjectName("sexLayout_2")
        self.male_button = QtWidgets.QRadioButton(parent=self.formLayoutWidget)
        self.male_button.setObjectName("male_button")
        self.sexLayout_2.setWidget(0, QtWidgets.QFormLayout.ItemRole.LabelRole, self.male_button)
        self.female_button = QtWidgets.QRadioButton(parent=self.formLayoutWidget)
        self.female_button.setTabletTracking(False)
        self.female_button.setAcceptDrops(False)
        self.female_button.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
        self.female_button.setObjectName("female_button")
        self.sexLayout_2.setWidget(0, QtWidgets.QFormLayout.ItemRole.FieldRole, self.female_button)
        self.formLayout.setLayout(2, QtWidgets.QFormLayout.ItemRole.FieldRole, self.sexLayout_2)
        self.ethnicity_input = QtWidgets.QComboBox(parent=self.formLayoutWidget)
        self.ethnicity_input.setObjectName("ethnicity_input")
        self.ethnicity_input.addItem("")
        self.ethnicity_input.addItem("")
        self.ethnicity_input.addItem("")
        self.ethnicity_input.addItem("")
        self.ethnicity_input.addItem("")
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.ItemRole.FieldRole, self.ethnicity_input)
        self.label_5 = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label_5.setObjectName("label_5")
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_5)
        self.lineEdit_3 = QtWidgets.QLineEdit(parent=self.formLayoutWidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_3)
        self.label_6 = QtWidgets.QLabel(parent=self.formLayoutWidget)
        self.label_6.setObjectName("label_6")
        self.formLayout.setWidget(5, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_6)
        self.lineEdit_4 = QtWidgets.QLineEdit(parent=self.formLayoutWidget)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.formLayout.setWidget(5, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_4)
        self.addstu_button = QtWidgets.QPushButton(parent=Form)
        self.addstu_button.setGeometry(QtCore.QRect(70, 260, 121, 31))
        self.addstu_button.setObjectName("addstu_button")
        self.cancelstu_button = QtWidgets.QPushButton(parent=Form)
        self.cancelstu_button.setGeometry(QtCore.QRect(240, 260, 111, 31))
        self.cancelstu_button.setObjectName("cancelstu_button")

        # 添加拍照按钮
        self.photo_button = QtWidgets.QPushButton(parent=Form)
        self.photo_button.setGeometry(QtCore.QRect(70, 300, 280, 31))
        self.photo_button.setObjectName("photo_button")

        self.cancelstu_button.clicked.connect(self.reset)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "学生信息添加"))
        self.label.setText(_translate("Form", "姓名："))
        self.label_2.setText(_translate("Form", "学号："))
        self.label_3.setText(_translate("Form", "性别："))
        self.label_4.setText(_translate("Form", "民族："))
        self.male_button.setText(_translate("Form", "男"))
        self.female_button.setText(_translate("Form", "女"))
        self.ethnicity_input.setItemText(0, _translate("Form", "汉"))
        self.ethnicity_input.setItemText(1, _translate("Form", "维吾尔"))
        self.ethnicity_input.setItemText(2, _translate("Form", "哈萨克"))
        self.ethnicity_input.setItemText(3, _translate("Form", "藏族"))
        self.ethnicity_input.setItemText(4, _translate("Form", "其它"))
        self.label_5.setText(_translate("Form", "班级："))
        self.label_6.setText(_translate("Form", "专业："))
        self.addstu_button.setText(_translate("Form", "保存"))
        self.cancelstu_button.setText(_translate("Form", "取消"))
        self.photo_button.setText(_translate("Form", "拍照"))  # 设置拍照按钮文本

    def reset(self):
        self.lineEdit_3.setText("")
        self.lineEdit_4.setText("")
        self.lineEdit.setText("")
        self.lineEdit_2.setText("")
        self.male_button.setChecked(True)  
        self.ethnicity_input.setCurrentIndex(0)  
        self.photo = None  # 重置照片数据
        
    def take_photo(self):
        cap = cv2.VideoCapture(0)
        if not cap.isOpened():
            QMessageBox.critical(self, "错误", "无法打开摄像头！")
            return

        ret, frame = cap.read()
        if ret:
            _, buffer = cv2.imencode('.jpg', frame)
            self.photo = buffer.tobytes()
            QMessageBox.information(self, "成功", "拍照成功！")
        else:
            QMessageBox.critical(self, "错误", "拍照失败！")

        cap.release()

    def add(self):
        Student.name = self.lineEdit.text().strip()          
        Student._stu_id = self.lineEdit_2.text().strip()      
        Student.class_info = self.lineEdit_3.text().strip()   
        Student.major = self.lineEdit_4.text().strip()       
        Student.gender = "男" if self.male_button.isChecked() else "女"  
        Student.ethnicity = self.ethnicity_input.currentText()  
        Student.dorm_building = None
        Student.dorm_num = None

        if not all([Student.name, Student._stu_id]):
            QMessageBox.warning(self, "警告", "姓名和学号不能为空！")
            return

        if self.photo is None:
            QMessageBox.warning(self, "警告", "请先拍照！")
            return

        try:
            # 连接到数据库
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()

            # 检查学号是否已存在
            cursor.execute("SELECT student_id FROM student_info WHERE student_id = ?", (Student._stu_id,))
            existing_student = cursor.fetchone()

            if existing_student:
                QMessageBox.warning(self, "警告", "该学号已存在！")
                conn.close()
                return

            # 检查学号是否为 4 位
            if not re.match(r'^\d{4}$', Student._stu_id):
                QMessageBox.warning(self, "警告", "学号必须为 4 位！")
                conn.close()
                return

            # 插入新学生信息，包含图片数据
            cursor.execute('''
                INSERT INTO student_info (name, student_id, gender, ethnicity, class_info, major, dorm_building, dorm_num, photo)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (Student.name, Student._stu_id, Student.gender, Student.ethnicity, Student.class_info, Student.major, Student.dorm_building, Student.dorm_num, self.photo))

            conn.commit()
            QMessageBox.information(self, "成功", "学生信息添加成功！")
            log_db.log("教师端","1000","添加学生",Student._stu_id)
            self.reset()

            conn.close()

        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")




if __name__ == '__main__':
    app = QApplication(sys.argv)

    ui = Ui_Form()
    ui.show()

    sys.exit(app.exec())